// https://leetcode.cn/problems/deepest-leaves-sum/
// Created by ade on 2022/8/17.
//

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    /*int sum = 0;
    int height = 0;

    int deepestLeavesSum(TreeNode *root) {
        height = getHeight(root);
        dfs(root, 0);
        return sum;
    }

    int getHeight(TreeNode *node) {
        if (!node) return 0;
        return max(getHeight(node->left), getHeight(node->right)) + 1;
    }

    void dfs(TreeNode *node, int index) {
        if (!node) return;
        if (index == height - 1) sum += node->val;
        dfs(node->left, index + 1);
        dfs(node->right, index + 1);
    }*/

    int sum = 0;
    int height = -1;

    int deepestLeavesSum(TreeNode *root) {
        dfs(root, 0);
        return sum;
    }

    void dfs(TreeNode *node, int index) {
        if (!node) return;

        if (height < index) {
            sum = node->val;
            height++;
        } else if (height == index) {
            sum += node->val;
        }

        dfs(node->left, index + 1);
        dfs(node->right, index + 1);
    }
};